function [schidx,nsidx] = RandomWalkSelectFcn(sch,schidx)
% [schidx,nsidx] = RandomWalkSelectFcn(sch,schidx)
%
%  Select the next trial index (NSIDX) based on a random walk algorithm.
%  If last trial was at a boundry, (i.e. lastidx == length(SCHIDX) ||
%  lastidx == 1), then the neighbouring index is selected.  In addition,
%  'silent' trials are inserted where the stimulus fades from current
%  frequency to quiet (amplitude = 0) and then back to the next selected
%  frequency.
%
%  Takes the schedule and schidx as input.
%       SCH is the schedule structure
%       SCHIDX is a 1D matrix with the number of rows equal to the number
%           of unique trials; i.e. size(trials,1).
%  Returns an updated version of SCHIDX and NSIDX
%       NSIDX is the next schedule trial index, i.e. the next index
%           selected from the SCH.trials matrix to run.
%       SCHIDX should be updated with the number of runs for each unique
%           trial in SCH.trials.  The returned version should have
%           SCHIDX(NSIDX) incremented.
%
%  This same format for input and output paramters must be met for custom
%  trial select functions (i.e., experiment.trialselectfcn);
%
%  DJS (c) 2011

global G_RP

persistent Fs RW TT % 'random walk' between trials generated on first call

if ~isfield(sch,'trial_idx'), sch.trial_idx = 1; end
curtrial = sch.trial_idx;
trials   = sch.trials;
boxid    = sch.boxid;

fidx = findincell(strfind(sch.writeparams,'FreqList'));

% which module?
writemod = sch.writemodule(fidx);
RP = G_RP(writemod);

if curtrial == 1
    % first trial: initialize SCHIDX and select first trial (NSIDX) at random
    schidx = zeros(size(trials,1),1); % initialize SCHIDX

    % Randomize trial sequences
    %
    % Trial Type Codes (TT)
    %       0 = normal frequency sweep trial
    %       1 = catch trial
    %       2 = fade out trial
    %       3 = fade in trial
    ub = length(schidx);
    lb = 1;
    
    r = rand(10^4,1);
    flag = true;
    k = 1;
    RW(1) = 1;
    for i = 2:length(r)
        k = k + 1;
        if ~flag && r(i) < 0.2
            % catch trial
            RW(k) = RW(k-1);
            TT(k-1) = 1;
            flag = true;
            
        elseif ~flag && r(i) < 0.7 
            % fade trial sequence
            % Fade Out always precedes Fade In
            RW(k:k+1) = RW(k-1);
            TT(k-1:k) = [2 3];
            flag = true;
            k = k + 1;
            
        else % frequency sweep
            if RW(k-1) == lb
                RW(k) = lb+1;
            elseif RW(k-1) == ub
                RW(k) = ub-1;
            else
                RW(k) = RW(k-1)+sign(randn(1));
            end
            TT(k-1) = 0;
            flag = false;
        end    
    end
        
    Fs = RP.GetSFreq;
end

% wait until previous sweep is over
while RP.GetTagVal(sprintf('stimstate~%d',boxid)), pause(0.05); end
% give some breathing room
pause(0.5);

% reset trial before setting new parameters
RP.SoftTrg(boxid);

% Update RPvds ------------------------------------------------------------
RP.SetTagVal(sprintf('trial_type~%d', boxid),TT(curtrial)); % Set new trial type

% current frequency
fbase = trials{RW(curtrial),fidx};

% next schedule index (nsidx)
nsidx = RW(curtrial+1);

% next frequency
fnext = trials{nsidx,fidx};

% update frequency sweep parameters for normal trials
if TT(curtrial) == 0
    if fnext > fbase % sweep up
        RP.SetTagVal(sprintf('FreqMin~%d', boxid),fbase);
        RP.SetTagVal(sprintf('FreqMax~%d', boxid),fnext);
        
    else % sweep down
        RP.SetTagVal(sprintf('FreqMin~%d', boxid),fnext);
        RP.SetTagVal(sprintf('FreqMax~%d', boxid),fbase);
        
    end
    RP.SetTagVal(sprintf('FreqBase~%d',boxid),fbase);
    
    fstep = (fnext - fbase) / floor(Fs/2); % sweep rate (0.5 seconds)
    RP.SetTagVal(sprintf('FreqStep~%d',boxid),fstep);
    RP.SoftTrg(boxid+2); % reset FStep following update
end

% workspace reporting for testing -----------------------------------------
% switch TT(curtrial)
%     case 0,    disp('-> Frequency Sweep Trial');
%     case 1,    disp('-> CATCH TRIAL');
%     case 2,    disp('-> FADE OUT TRIAL');
%     case 3,    disp('-> FADE IN TRIAL');
% end
% assignin('base','sch',sch);
% assignin('base','RW',RW);


% update SCHIDX
schidx(nsidx) = schidx(nsidx) + 1;





